package cn.gailvlun.gll.presentation.emotion;

import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Html;
import android.text.Spanned;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.github.markzhai.recyclerview.BaseViewAdapter;
import com.github.markzhai.recyclerview.BindingViewHolder;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import cn.gailvlun.gll.R;
import cn.gailvlun.gll.databinding.FragmentEmotionSquareBinding;
import cn.gailvlun.gll.net.HttpMethods;
import cn.gailvlun.gll.net.HttpSubscriber;
import cn.gailvlun.gll.net.ListRes;
import cn.gailvlun.gll.net.emotion.Emotion;
import cn.gailvlun.gll.net.emotion.EmotionEnum;
import cn.gailvlun.gll.net.emotion.EmotionHeartReq;
import cn.gailvlun.gll.net.emotion.EmotionSquareReq;
import cn.gailvlun.gll.presentation.base.App;
import cn.gailvlun.gll.presentation.base.BaseFragment;
import cn.gailvlun.gll.presentation.chat.PhotoActivity;
import cn.gailvlun.gll.presentation.emotion.bean.EmotionDetailTransfer;
import cn.gailvlun.gll.presentation.emotion.util.EmotionDateUtil;
import cn.gailvlun.gll.presentation.emotion.widget.EmotionDecoration;
import cn.gailvlun.gll.presentation.profile.OtherProfileActivity;
import cn.gailvlun.gll.presentation.profile.ProfileActivity;
import cn.gailvlun.gll.util.DialogUtil;
import cn.gailvlun.gll.util.IsEmpty;
import cn.gailvlun.gll.util.LogUtil;
import cn.gailvlun.gll.util.ProfileUtil;
import cn.gailvlun.gll.util.RxUtil;



@Deprecated
public class EmotionSquareFragment extends BaseFragment {

    public final static String START_POS = "start_pos";
    public final static String CURRENT_POS = "current_pos";

    public static EmotionSquareFragment newInstance(EmotionEnum emotionEnum) {
        EmotionSquareFragment emotionSquareFragment = new EmotionSquareFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("emotion", emotionEnum);
        emotionSquareFragment.setArguments(bundle);
        return emotionSquareFragment;
    }

    private FragmentEmotionSquareBinding mBinding;
    private EmotionEnum mEmotionEnum;

    private EmotionSquareAdapter mAdapter;
    private LinearLayoutManager mLayoutManager;
    private EmotionSquareReq req;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mEmotionEnum = (EmotionEnum) getArguments().getSerializable("emotion");
    }

    @Override
    protected boolean isLazyLoad() {
        return true;
    }

    @Override
    protected View initComponent(@NonNull LayoutInflater inflater, @Nullable ViewGroup container) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_emotion_square, container, false);
        mBinding.setEmotion(mEmotionEnum);

        mAdapter = new EmotionSquareAdapter(getContext());
        mAdapter.setPresenter(new Presenter());
        mAdapter.setDecorator(new BaseViewAdapter.Decorator() {
            @Override
            public void decorator(BindingViewHolder holder, int position, int viewType) {
                ViewDataBinding itemBinding = holder.getBinding();
















            }
        });
        mBinding.rvEmotionList.setAdapter(mAdapter);

        mLayoutManager = new LinearLayoutManager(mContext);
        mBinding.rvEmotionList.setLayoutManager(mLayoutManager);

        mBinding.rvEmotionList.addItemDecoration(new EmotionDecoration(mContext));
        return mBinding.getRoot();
    }

    @Override
    protected void createHandler() {
        mBinding.srl.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                req.setLoadMore(true);
                getData(req);
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                req.setLoadMore(false);
                getData(req);
            }
        });
    }

    public void autoRefresh() {
        mBinding.srl.autoRefresh();
    }

    private void getData(@NonNull final EmotionSquareReq req) {
        

        HttpMethods.getEmotionService().emotionListG(req.getId(),
                req.getDirection(),null,null)
                .compose(RxUtil.<ListRes<Emotion>>applyScheduler())
                .subscribe(new HttpSubscriber<ListRes<Emotion>>() {
                    @Override
                    protected void onSuccess(ListRes<Emotion> response) {
                        LogUtil.d("emotion square request success");
                        mBinding.setCount(response.getCount());
                        mBinding.invalidateAll();
                        mBinding.srl.setEnableLoadmore(response.isNext());
                        if (response.getResults().size() > 0) {
                            int lastIndex = response.getResults().size() - 1;
                            req.setId(response.getResults().get(lastIndex).getId());
                        }
                        if (req.isLoadMore()) {
                            mAdapter.addAll(response.getResults(), EmotionSquareAdapter.Type.CONTENT.ordinal());
                        } else {
                            mBinding.invalidateAll();
                            mAdapter.clear();
                            if (IsEmpty.list(response.getResults())) {
                                mAdapter.add(null, EmotionSquareAdapter.Type.EMPTY.ordinal());
                            } else {
                                mAdapter.addAll(response.getResults(), EmotionSquareAdapter.Type.CONTENT.ordinal());
                            }
                        }
                        mBinding.srl.finishLoadmore(0);
                        mBinding.srl.finishRefresh(0);
                    }

                    @Override
                    protected void onFailure(String errMsg, @Nullable ListRes<Emotion> response, int code) {
                        DialogUtil.showError(mContext, errMsg);
                        mBinding.srl.finishLoadmore(0);
                        mBinding.srl.finishRefresh(0);
                    }
                });
    }








    @Override
    protected void loadData(@Nullable Bundle savedInstanceState) {
        req = new EmotionSquareReq();
        mBinding.srl.autoRefresh();

    }

    @Override
    protected void onVisible() {
        super.onVisible();

        mBinding.srl.autoRefresh();
    }

    public class Presenter implements BaseViewAdapter.Presenter {
        public void jump2Profile(Emotion item) {
            Integer myId = ProfileUtil.getUserId();
            if (myId != null && item.getOwner().getId() == myId) {
                ProfileActivity.openActivity(mContext);
            } else {
                OtherProfileActivity.openActivity(mContext, item.getOwner());
            }
        }

        public void toEmotionDetail(Emotion model) {
            EmotionDetailTransfer transfer = new EmotionDetailTransfer();
            transfer.setId(model.getId());
            Integer userId = ProfileUtil.getUserId();
            if (userId != null && model.getOwner().getId() == userId) {
                transfer.setTitle(R.string.emotion_my_emotion);
            }
            EmotionDetailActivity.openActivity(mContext, transfer);
        }

        public String getTime(Emotion model) {
            return EmotionDateUtil.commentTimeFormat(model.getCreated());
        }

        public void emotionHeart(final Emotion emotion) {
            EmotionHeartReq req = new EmotionHeartReq(emotion.getId(), emotion.getHeart().isHearted() ? -1 : 1);
            HttpMethods.getEmotionService().emotionHeart(req)
                    .compose(RxUtil.<Emotion>applyScheduler())
                    .subscribe(new HttpSubscriber<Emotion>() {
                        @Override
                        protected void onSuccess(Emotion response) {
                            
                            emotion.setHeart(response.getHeart());
                            mAdapter.notifyDataSetChanged();
                        }

                        @Override
                        protected void onFailure(String errMsg, @Nullable Emotion response, int code) {
                            DialogUtil.showError(mContext, errMsg);
                        }
                    });
        }

        public void onClickImage(View iv, Emotion item, int position) {
            ActivityOptionsCompat options = ActivityOptionsCompat
                    .makeSceneTransitionAnimation(getActivity(), iv,
                            App.getInstance().getString(R.string.shared_image));
            PhotoActivity.openActivity(mContext, item.getPics().get(position), options.toBundle());
        }
    }

    public static class Util {
        public static Spanned getTitle(EmotionEnum emotionEnum, Integer count) {
            if (count == null) {
                count = 0;
            }
            String mode = App.getInstance().getString(R.string.emotion_square_count_format,
                    count, emotionEnum.getDesc());
            return Html.fromHtml(mode);
        }

        public static String getImageUrl(Emotion item, int position) {
            if (position < item.getPics().size()) {
                return item.getPics().get(position);
            } else {
                return null;
            }
        }

        public static int getImageCount(Emotion item) {
            return item.getPics().size();
        }

        public static Drawable getSameIcon(Emotion item) {
            if (item == null) {
                return null;
            }
            return App.getInstance().getResources().getDrawable(
                    item.getHeart().isHearted() ? R.drawable.ic_love_selected :
                            R.drawable.ic_love_unselected
            );
        }
    }
}
